package cn.itcast.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义全局过滤器
 *
 * 需求：定义全局过滤器，拦截请求，判断请求的参数是否满足下面条件：
 *
 *
 * ● 参数中是否有authorization，
 * ● authorization参数值是否为admin
 *
 * ❈ 如果同时满足则放行，否则拦截
 */
@Component
@Order(-1)
public class AuthorizationFilter implements GlobalFilter {
    /**
     * 过滤规则方法实现
     * @param exchange 封装了请求上下文的信息,包含了 request response 等
     * @param chain 过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取url地址的参数
        MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
        String admin = queryParams.getFirst("authorization");
        if("admin".equals(admin)){
            //满足条件放行
            return chain.filter(exchange);
        }
        //不满足则拒绝 状态码:403
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        return exchange.getResponse().setComplete();
    }
}
